<template>
  <van-field
    v-model="result"
    :label="props.label"
    placeholder="点击选择"
    :required="props.required"
    @click="showPicker = true"
    is-link
    center
    v-if="
      props.Type == 'select' || props.Type == 'dateTime' || props.Type == 'date'
    "
    :rules="[{ required: props.required, message: '请选择' }]"
    clearable
    clear-trigger="always"
    :label-width="props.labelWidth"
    @clear="clearValue"
  >
    <template #input>
      {{ result }}
      <span v-show="!result" class="fieldPlaceholder">请选择</span>
    </template>
  </van-field>
  <van-field
    v-if="props.Type == 'textarea'"
    v-model="result"
    rows="2"
    autosize
    :label="props.label"
    type="textarea"
    :required="props.required"
    maxlength="50"
    placeholder="请输入"
    show-word-limit
    clearable
    :rules="[{ required: props.required, message: '请输入' }]"
    clear-trigger="always"
    :label-align="props.labelAlign"
    :label-width="props.labelWidth"
  >
  </van-field>

  <van-field
    v-if="props.Type == 'digit'"
    v-model="result"
    :label="props.label"
    type="digit"
    placeholder="请输入"
    :required="props.required"
    clearable
    clear-trigger="always"
    :label-width="props.labelWidth"
  >
  </van-field>
  <van-field
    v-if="props.Type == 'input'"
    v-model="result"
    :label="props.label"
    placeholder="请输入"
    :required="props.required"
    clearable
    clear-trigger="always"
    :readonly="props.readonly"
    :rules="props.rules"
    :label-width="props.labelWidth"
  >
  </van-field>
  <van-field
    v-if="props.Type == 'calendar'"
    v-model="result"
    is-link
    name="calendar"
    :label="props.label"
    placeholder="点击选择"
    :required="props.required"
    :rules="[{ required: props.required, message: '请选择' }]"
    @click="showCalendar = true"
    clearable
    clear-trigger="always"
    :label-width="props.labelWidth"
    @clear="clearValue"
  >
    <template #input>
      {{ result }}
      <span v-show="!result" class="fieldPlaceholder">请选择</span>
    </template>
  </van-field>
  <!-- 文件 -->
  <van-field
    name="uploader"
    :required="props.required"
    :label="props.label"
    v-if="props.Type == 'file'"
    :label-align="props.labelAlign"
    :label-width="props.labelWidth"
    :label-class="props.labelWeight ? 'labelWeight' : 'nolabelWeight'"
    :rules="[{ required: props.required, message: '请选择' }]"
    v-model="result"
  >
    <template #input>
      <fileUpload
        :mobile="true"
        :showSort="props.showSort"
        :detail="props.detail"
        v-model:fileList="fileList"
        :showBtn="props.showBtn"
        @getItem="handleGetItem"
      ></fileUpload>
    </template>
  </van-field>

  <!-- 级联 -->
  <van-field
    v-model="result"
    :required="props.required"
    is-link
    v-if="props.Type == 'cascader'"
    :label="props.label"
    clearable
    placeholder="请选择"
    :label-width="props.labelWidth"
    clear-trigger="always"
    @click="showCascader = true"
    @clear="clearValue"
  >
    <template #input>
      {{ result }}
      <span v-show="!result" class="fieldPlaceholder">请选择</span>
    </template>
  </van-field>
  <van-popup v-model:show="showCascader" round position="bottom">
    <van-cascader
      v-model="cascaderValue"
      title="请选择"
      :options="options"
      @close="showCascader = false"
      @change="onChange"
      @finish="onFinish"
      :field-names="fieldNames"
    />
  </van-popup>

  <!-- 日历 -->
  <van-calendar v-model:show="showCalendar" @confirm="onConfirmCalendar" />
  <!-- 弹窗 -->
  <van-popup
    v-model:show="showPicker"
    position="bottom"
    round
    :style="{ height: '75vh' }"
    :closeable="props.closeable"
    safe-area-inset-top
    safe-area-inset-bottom
  >
    <div class="title" v-if="props.title">
      {{ props.label }}
    </div>

    <div v-if="props.Type == 'dateTime'">
      <van-picker-group
        :title="props.label"
        :tabs="['选择日期', '选择时间']"
        @confirm="onConfirmDateTime"
        @cancel="showPicker = false"
      >
        <van-date-picker v-model="currentDate" :min-date="props.minDate" />
        <van-time-picker
          v-model="currentTime"
          :columns-type="props.columnsType"
          :min-hour="props.minHour"
          :min-minute="props.minMinute"
          :min-second="props.minSecond"
        />
      </van-picker-group>
    </div>
    <div v-if="props.Type == 'date'">
      <van-picker-group
        :title="props.label"
        :tabs="['选择日期']"
        @confirm="onConfirmDateTime"
        @cancel="showPicker = false"
      >
        <van-date-picker v-model="currentDate" :min-date="props.minDate" />
      </van-picker-group>
    </div>

    <div v-if="props.Type == 'select'">
      <van-search
        v-model="queryParams[props.searchKey]"
        shape="round"
        background="#ddd"
        placeholder="请输入编号"
        show-action
      >
        <template #action>
          <van-button size="small" @click="onRefresh" type="primary"
            >搜 索</van-button
          >
        </template>
      </van-search>
      <!-- <van-pull-refresh v-model="refreshing" @refresh="onRefresh"> -->
      <div class="listContent">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
          offset="50"
        >
          <div class="content">
            <div
              class="item"
              v-for="(item, index) in tabList"
              :key="index"
              @click="ItemClick(item)"
            >
              <div class="label">
                {{ item.Name }}
              </div>
              <div class="value flex acenter"></div>
            </div>
          </div>
        </van-list>
      </div>
      <!-- </van-pull-refresh> -->
    </div>
  </van-popup>
</template>
<script setup name="Popover">
import { computed, onMounted, ref, watch, getCurrentInstance } from 'vue';
import { GetAreaList_Page } from '@/api/school/region.js';
import { GetPlaceList_Page } from '@/api/site/index.js';
import { GetSixSaleTypeList_Page } from '@/api/sixManage/problemType.js';
import { GetCourseTypeList_Page } from '@/api/lesson/lessonType.js';
import useUserStore from '@/store/modules/user.js';
import { GetCourseList_Page } from '@/api/lesson/lessonSystem.js';
import { listUser } from '@/api/system/user';

const { proxy } = getCurrentInstance();
const emit = defineEmits(['update:modelValue', 'select']);
const props = defineProps({
  modelValue: {
    default: ''
  },
  label: {
    default: '区域'
  },
  required: {
    default: true
  },
  query: {
    default: {}
  },
  Type: {
    default: 'select'
  },
  closeable: {
    default: true
  },
  title: {
    default: true
  },
  columnsType: {
    default: ['hour', 'minute', 'second']
  },
  labelAlign: {
    default: 'left'
  },
  category: {
    default: ''
  },
  showBtn: {
    default: true
  },
  labelWeight: {
    default: true
  },
  detail: {
    default: true
  },
  readonly: {
    default: false
  },
  searchKey: {
    default: 'Code'
  },
  labelWidth: {
    default: '70px'
  },
  minDate: {
    default: new Date('2022-01-01')
  },
  minHour: {
    default: 0
  },
  minMinute: {
    default: 0
  },
  minSecond: {
    default: 0
  },
  maxDate: {
    default: ''
  },
  rules: {
    default: []
  },
  showSort: {
    default: false
  },
  detail: {
    default: true
  }
});
const fieldNames = {
  text: 'Name',
  value: 'ID',
  children: 'children'
};
const currentTime = ref([]);
const currentDate = ref([]);
const showCascader = ref(false);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const total = ref(0);
const queryParams = ref({});
const showCalendar = ref(false);
const showPicker = ref(false);
const result = ref('');
const cascaderValue = ref('');
const page = ref({
  PageIndex: 0,
  PageSize: 10
});
const options = ref([]);
const searchValue = ref('');
const error = ref(false);
const tabList = ref([]);
const fileList = computed({
  get: () => props.modelValue,
  set: val => {
    emit('update:modelValue', val);
  }
});

watch(
  () => result.value,
  (n, o) => {
    if (props.Type == 'textarea') {
      emit('update:modelValue', n);
    }
    if (props.Type == 'calendar') {
      emit('update:modelValue', n);
    }
    if (props.Type == 'input') {
      emit('update:modelValue', n);
    }
    if (props.Type == 'digit') {
      emit('update:modelValue', n);
    }
  }
);
watch(
  () => props.modelValue,
  (n, o) => {
    if (!n) {
      if (props.Type == 'textarea') {
        result.value = '';
      }
    }
  }
);
watch(
  () => props.query,
  (n, o) => {
    if (JSON.stringify(n) == JSON.stringify(o)) return;
    tabList.value = [];
    result.value = '';
    emit('update:modelValue', '');
    init();
  },
  {
    deep: true
  }
);

onMounted(() => {
  if (props.Type == 'cascader') {
    initCascader();
  }
});

async function initCascader() {
  let list = [];
  switch (props.category) {
    case '课程级联':
      list = await getCourseType();
      break;
    default:
      return;
  }
  options.value = list;
}

async function init() {
  let res = {};
  switch (props.category) {
    case '区域':
      res = await getArea();
      break;
    case '场地':
      res = await getPlace();
      break;
    case '6S类型':
      res = await getSixType();
      break;
    case '全部用户':
      res = await getAlluser();
      break;
    case '用户列表':
      res = await getUserList();
      break;
    default:
      return;
  }
  console.log(res.data.List);
  tabList.value = [...tabList.value, ...res.data.List];
  total.value = res.data.Total;
  loading.value = false;
  if (tabList.value.length >= total.value) {
    //将返回数据长度与总条数进行比较控制加载不加载的状态
    finished.value = true;
  }
}

const onFinish = async ({ selectedOptions }) => {
  switch (props.category) {
    case '课程级联':
      let obj = selectedOptions[selectedOptions.length - 1];
      if (!obj.Mode) return;
      emit('update:modelValue', obj.ID);
      result.value = selectedOptions.map(option => option.Name).join('/');
      showCascader.value = false;
      break;
    default:
      return;
  }
};

const onChange = async ({ value, tabIndex }) => {
  switch (props.category) {
    case '课程级联':
      let res = await GetCourseList_Page({ Type: value, NoPage: 'true' });
      options.value[tabIndex].children = res.data;
      break;
  }
};

function onConfirmCalendar(val) {
  if (props.Type == 'calendar') {
    result.value = proxy.$moment(val).format('YYYY-MM-DD');
    showCalendar.value = false;
  }
}

function onConfirmDateTime(val) {
  if (props.Type == 'dateTime') {
    let time =
      val[0]?.['selectedValues'].join('-') +
      ' ' +
      val[1]?.['selectedValues'].join(':');
    emit('update:modelValue', time);
    result.value = time;
    showPicker.value = false;
  } else {
    let time = val[0]?.['selectedValues'].join('-');
    emit('update:modelValue', time);
    result.value = time;
    showPicker.value = false;
  }
}

function handleGetItem(val) {
  result.value = val.length ? val.length : '';
}

function ItemClick(item) {
  showPicker.value = false;
  emit('update:modelValue', item.ID);
  emit('select', item);
  result.value = item.Name;
}
const onLoad = () => {
  console.log('触底');
  if (refreshing.value) {
    tabList.value = [];
    refreshing.value = false;
  }
  setTimeout(() => {
    page.value.PageIndex++;
    init();
  }, 500);
};

const onRefresh = () => {
  // 清空列表数据
  finished.value = false;
  tabList.value = [];
  page.value.PageIndex = 0;
  loading.value = true;
  onLoad();
};
//清空值
function clearValue() {
  result.value = '';
  emit('update:modelValue', '');
  showPicker.value = false;
}

//获取课程类型
async function getCourseType() {
  try {
    let query = {
      Code: '',
      Name: '',
      NoPage: 'true'
    };
    let res = await GetCourseTypeList_Page(query);
    return res.data;
  } catch (error) {
    console.log(error);
  }
}
//用户列表
async function getUserList() {
  try {
    let query = {
      Code: '',
      Name: '',
      ...page.value,
      NoPage: '',
      ...props.query,
      ...queryParams.value
    };
    return await listUser(query);
  } catch (error) {
    console.log(error);
  }
}
//全部用户
async function getAlluser() {
  let List = useUserStore().allUserList;
  return {
    data: {
      List,
      Total: List.length
    }
  };
}
//6s类型
async function getSixType() {
  try {
    let query = {
      Code: '',
      Name: '',
      ...page.value,
      NoPage: '',
      ...props.query,
      ...queryParams.value
    };
    return await GetSixSaleTypeList_Page(query);
  } catch (error) {
    console.log(error);
  }
}
//获取区域
async function getArea() {
  try {
    let query = {
      Code: '',
      Name: '',
      ...page.value,
      NoPage: '',
      ...props.query,
      ...queryParams.value
    };
    return await GetAreaList_Page(query);
  } catch (error) {
    console.log(error);
  }
}
//获取场地
async function getPlace() {
  try {
    let query = {
      Code: '',
      Name: '',
      ...page.value,
      NoPage: '',
      ...props.query,
      ...queryParams.value
    };
    return await GetPlaceList_Page(query);
  } catch (error) {
    console.log(error);
  }
}
</script>

<style lang="scss" scoped>
.title {
  text-align: center;
  height: 50px;
  line-height: 50px;
}

.content {
  .item {
    padding: 10rpx;
    border-bottom: 1px solid #ddd;

    &:last-child {
      // border: none;
    }
  }
}

:deep(.labelweight label) {
  font-weight: 700 !important;
}

:deep(.nolabelWeight label) {
  font-weight: 500 !important;
}
.listContent {
  height: calc(75vh - 108px);
  overflow-y: scroll;
}
.fieldPlaceholder {
  color: rgb(190, 187, 187);
}
</style>
